package com.hd.trans.ui.service;

import android.os.CountDownTimer;

import com.hd.trans.common.interf.Callback;
import com.hd.trans.network.ApiServiceManager;
import com.hd.trans.network.ParamJson;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.RxSchedulers;
import com.hd.trans.network.bean.AliTokenResponse;
import com.hd.trans.network.bean.TimeResponse;
import com.hd.trans.utils.LogUtil;

public class NetworkTaskService {
    private static NetworkTaskService mInstance;
    private boolean isTimeOk;
    private boolean isAliTokenOk;
    private CountDownTimer timer;

    public NetworkTaskService() {
        isTimeOk = false;
        isAliTokenOk = false;
    }

    public static NetworkTaskService getInstance() {
        if(mInstance == null) {
            mInstance = new NetworkTaskService();
        }
        return mInstance;
    }

    public void start() {
        if(isTimeOk && isAliTokenOk) {
            return;
        }
        requestServiceTime(() -> {
            if(!isAliTokenOk){
                requestAliToken();
            }
        });
    }

    /**
     * 同步服务器时间
     */
    public void syncServiceTime(Callback callback){
        requestServiceTime(callback);
    }

    private void actionTimer(long time) {
        if(timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimer(time, time) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                requestAliToken();
            }
        };
        timer.start();
    }

    private void requestServiceTime(Callback callback) {
        ApiServiceManager.INSTANCE.getApiService()
                .getServiceTime()
//                .compose(bindToLifecycle())
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver<>(new NetDisposableObserver.NetCallBack<TimeResponse>() {
                    @Override
                    public void onResponse(TimeResponse response) {
                        if (response != null) {
                            isTimeOk = true;
                            PreferenceMgr.getInstance().saveServerTimeStamp(response.getUtctime() * 1000);
                            LogUtil.d("同步服务器时间完成");
                        }
                        if(callback != null) {
                            callback.onCallback();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        LogUtil.e("NetworkTaskService :code " + code + " msg: " + msg);
                        if(callback != null) {
                            callback.onCallback();
                        }
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        if(callback != null) {
                            callback.onCallback();
                        }
                    }
                }));

    }


    private void requestAliToken() {
        ApiServiceManager.INSTANCE.getApiService()
                .getAlitoken(new ParamJson.CommonParam())
//                .compose(bindToLifecycle())
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver<>(new NetDisposableObserver.NetCallBack<AliTokenResponse>() {
                    @Override
                    public void onResponse(AliTokenResponse response) {
                        if (response != null) {
                            isAliTokenOk = true;
                            PreferenceMgr.getInstance().getTranslatePreference().saveAliToken(response.getTasktoken());

                            /** 在此处延迟请求 */
                            long timeExpired = Math.max(60, response.getTimestamp() - response.getUploadtime());
                            actionTimer(timeExpired * 1000);
                            LogUtil.d("阿里云token获取完成");
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        LogUtil.e("NetworkTaskService :code" + code + " msg:" + msg);
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        LogUtil.w(msg);
                    }
                }));

    }
}
